<template>
    <div>
        <Title :title="title"></Title>
        <div ref="right2" style="height: 150px;"></div>
        <!-- 数据状态提示 -->
        <div v-if="dataStatus === 'error'" class="status提示">
            数据加载失败，请稍后重试
        </div>
        <div v-if="dataStatus === 'empty'" class="status提示">
            暂无有效数据
        </div>
    </div>
</template>
<script>
import { Bar } from '@antv/g2plot';
import { get } from '@/utils/request';
import moment from 'moment';

export default {
    data() {
        return {
            title: '实时颗粒物曲线',
            PmData: [],
            barChart: null,
            dataStatus: 'loading' // 状态：loading/error/empty/success
        }
    },
    methods: {
        async fetchPmData() {
            try {
                const response = await get('http://106.14.227.138:7001/dashboard/pageQueryTodayData', {
                    page: 1,
                    pageSize: 10,
                    startTime: moment().subtract(4, 'hours').toISOString(),
                    endTime: moment().toISOString()
                });

                const hasValidData = response.data?.list && response.data.list.length > 0;
                if (hasValidData) {
                    this.PmData = this.transformData(response.data.list);
                    this.dataStatus = this.PmData.length > 0 ? 'success' : 'empty';
                } else {
                    this.dataStatus = 'empty';
                }
            } catch (error) {
                console.error('数据请求失败:', error);
                this.dataStatus = 'error';
                this.PmData = [];
            }
        },

        transformData(rawList) {
            const transformed = [];
            rawList.forEach(item => {
                const timeStr = item.insert_time || item.insertTime;
                if (!timeStr) return;

                const time = moment(timeStr).format('HH:mm');
                if (item.pm25 !== undefined && item.pm10 !== undefined) {
                    transformed.push(
                        { time: time, type: 'PM2.5', concentration: Number(item.pm25) },
                        { time: time, type: 'PM10', concentration: Number(item.pm10) }
                    );
                }
            });
            return transformed;
        },

        loadPmBar() {
            if (this.barChart) {
                this.barChart.destroy();
                this.barChart = null;
            }

            if (this.dataStatus === 'success' && this.PmData.length > 0) {
                this.barChart = new Bar(this.$refs.right2, {
                    data: this.PmData,
                    isGroup: true,
                    xField: 'concentration',
                    yField: 'time',
                    seriesField: 'type',
                    color: ['#1890ff', '#fa8c16'],
                    legend: {
                        position: 'top-left',
                        itemName: { 
                            style: { 
                                fontSize: 12,
                                fill: 'pink',  // 保持PM10和PM2.5标识符为pink
                                opacity: 1
                            } 
                        }
                    },
                    xAxis: {
                        label: { 
                            formatter: v => `${v}μg/m³`,
                            style: {
                                fill: '#ffffff',
                                opacity: 1
                            }
                        },
                        title: {
                            text: 'concentration',
                            style: {
                                fill: 'orange',  // concentration标题为orange
                                opacity: 1
                            }
                        },
                        min: 0
                    },
                    yAxis: {
                        label: {
                            style: {
                                fill: '#ffffff',
                                opacity: 1
                            }
                        },
                        title: {
                            text: 'time',
                            style: {
                                fill: 'orange',  // time标题为orange
                                opacity: 1
                            }
                        }
                    },
                    label: {
                        position: 'middle',
                        layout: [
                            { type: 'interval-adjust-position' },
                            { type: 'interval-hide-overlap' },
                            { type: 'adjust-color' }
                        ],
                        style: {
                            fill: 'orange',  // 数值标签为orange
                            opacity: 1
                        }
                    }
                });

                this.barChart.render();
            }
        }
    },
    async mounted() {
        await this.fetchPmData();
        this.$nextTick(() => this.loadPmBar());
    },
    beforeDestroy() {
        if (this.barChart) this.barChart.destroy();
    }
}
</script>
<style scoped>
::v-deep .g2-tooltip {
    background: #fff;
    border: 1px solid #e8e8e8;
    border-radius: 4px;
    padding: 5px 10px;
}

::v-deep .g2-tooltip-item {
    display: flex;
    align-items: center;
    margin: 3px 0;
}

.status提示 {
    height: 150px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #666;
    font-size: 14px;
}
</style>